<template>
  <div class="container">
    <div class="statistics">
      <el-statistic title="当前文件(点击切换)">
        <template slot="formatter">
          <div class="filename" @click="showDrawer = true">{{selectFilename}}</div>
        </template>
      </el-statistic>
      <el-statistic title="数据总量">
        <template slot="formatter">
          {{dataCount}}
        </template>
      </el-statistic>
    </div>

    <div class="echarts">
      <div class="top-echarts">
        <div class="disease-bar"></div>
        <div class="word-cloud"></div>
      </div>
      <div class="bottom-echarts" style="margin-top: 10px;">
        <div class="age-funnel"></div>
        <div class="gender-pie"></div>
      </div>
    </div>

    <el-drawer
        title="切换数据表格"
        :visible.sync="showDrawer"
        direction="rtl">
      <div class="tips">
        <div class="tips-icon"><img src="../assets/image/excel.png" alt="" style="width: 100%;height: 100%" /></div>
        <div class="tips-text">请选择要进行数据分析的表格。</div>
      </div>
      <el-select v-model="selectFilename" placeholder="请选择要进行数据分析的表格" style="width: 98%; margin-left: 4px" size="small" @change="selectChange">
        <el-option
            v-for="item in fileOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <div class="tips" style="margin-top: 10px">
        <div class="tips-icon"><img src="../assets/image/not_find.png" alt="" style="width: 100%;height: 100%" /></div>
        <div class="tips-text">没找到所需要文件？在下方上传。</div>
      </div>
      <el-upload
          class="upload-file"
          drag
          action="https://yiyuy.mynatapp.cc/model/uploadCsv"
          :on-exceed="handleCsvExceed"
          :on-remove="handleCsvRemove"
          :on-progress="handleCsvProgress"
          :on-success="handleCsvSuccess"
          :on-error="handleError"
          accept=".csv,.xlsx"
          :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将CSV/XLSX文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传CSV/XLSX文件，请勿上传较大文件</div>
      </el-upload>
    </el-drawer>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-wordcloud'
import {analysisDataByFile, getAllTable} from "@/api/data";
const animationDuration = 2000
export default {
  name: 'DataAnalysis',
  data() {
    return {
      // 是否显示切换数据表格的抽屉
      showDrawer: false,
      // 选择要进行数据分析的表格的名称
      selectFilename: 'InitLabel.csv',
      // 全部可以数据分析的表格
      fileOptions: [],
      // 各类疾病数量 x轴值 y轴值
      diseaseBarDataX: ['N', 'D', 'G', 'C', 'A', 'H', 'M', 'O'],
      diseaseBarDataY: [0, 0, 0, 0, 0, 0, 0, 0],
      // 词云频率
      wordCloud: [],
      // 年龄分级
      ageCount: [],
      // 性别比例
      genderCount: [],
      // 数据总量
      dataCount: []
    }
  },
  mounted() {
    this.getTableOptions();
    this.analysisData()
  },
  methods: {
    // CSV超出时调用的函数
    handleCsvExceed(files, fileList) {
      this.$message.error('最多只能上传一个CSV/XLSX文件')
    },
    handleCsvRemove(files, fileList) {
      this.$message.success('文件移除成功')
    },
    handleCsvProgress(event, files, fileList){
      this.$message.warning('文件上传中...')
    },
    handleCsvSuccess(response, file, fileList) {
      if ( response.code !== 200 ) {
        return this.$message.error(response.message)
      }

      this.getTableOptions();
      this.selectFilename = response.data
      this.analysisData();
      this.$message.success('文件上传成功')
    },
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 当选择发生变化时 重新获取数据渲染图表
    selectChange(value) {
      console.log(value)
      this.selectFilename = value
      this.analysisData()
    },
    // 根据文件名找到对应文件并分析
    analysisData() {
      analysisDataByFile(this.selectFilename).then(res=> {
        this.diseaseBarDataY = res.data['diseaseCount']
        this.wordCloud = res.data['wordCloud']
        this.ageCount = res.data['ageCount']
        this.genderCount = res.data['genderCount']
        this.dataCount = res.data['Count']
        this.initDiseaseBar();
        this.initWordCloud();
        this.initAgeFunnel();
        this.initGenderPie();
      })
    },
    // 获取所有可以用来数据分析的表
    getTableOptions() {
      getAllTable().then(res =>{
        for (let i = 0 ; i < res.data.length ; i ++ ) {
          this.fileOptions.push({
            label: res.data[i],
            value: res.data[i]
          })
        }
      })
    },
    initDiseaseBar() {
      // macarons 使用macarons配色
      let barEcharts = echarts.init(document.querySelector('.disease-bar'));
      barEcharts.setOption({
        title: {
          text: '各类疾病数量统计',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        toolbox: {
          feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}
          }
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: this.diseaseBarDataX,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            interval: 0,
            rotate: 40
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '各类疾病数量',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: this.diseaseBarDataY,
          animationDuration
        }]
      })
    },
    initWordCloud() {
      let wordCloudEcharts = echarts.init(document.querySelector('.word-cloud'));
      wordCloudEcharts.setOption({
        title: {
          text: '疾病关键词词云',
        },
        tooltip: {
          show: true
        },
        toolbox: {
          feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}
          }
        },
        series: [{
          name: '疾病关键词词云',
          type: 'wordCloud',
          sizeRange: [12, 60],
          rotationRange: [-90, 90],
          shape: 'circle',
          gridSize: 8,
          width: '80%',
          height: '80%',
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
            // Color可以是一个回调函数或一个颜色字符串
            color: function () {
              // Random color
              return 'rgb(' + [
                Math.round(Math.random() * 255),
                Math.round(Math.random() * 255),
                Math.round(Math.random() * 255)
              ].join(',') + ')';
            }
          },
          emphasis: {
            focus: 'self',

            textStyle: {
              textShadowBlur: 10,
              textShadowColor: '#333'
            }
          },
          data: this.wordCloud,
          animationDuration
        }]
      })
    },
    initAgeFunnel() {
      let funnelEcharts = echarts.init(document.querySelector('.age-funnel'));
      funnelEcharts.setOption({
        title: {
          text: '患者年龄分布',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}人'
        },
        toolbox: {
          feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}
          }
        },
        legend: {
          top: '5%',
          data: ['30-40岁', '40-50岁', '50-60岁', '60-70岁', '70-80岁']
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        series: [{
          name: '患者年龄分布',
          type: 'funnel',
          left: '10%',
          top: 60,
          bottom: 60,
          width: '80%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 20
            }
          },
          data: this.ageCount,
          animationDuration
        }]
      })
    },
    initGenderPie() {
      let pieEcharts = echarts.init(document.querySelector('.gender-pie'), 'macarons');
      pieEcharts.setOption({
        title: {
          text: '患者男女比',
        },
        tooltip: {
          trigger: 'item'
        },
        toolbox: {
          feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}
          }
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '患者男女比',
            type: 'pie',
            radius: '60%',
            data: this.genderCount,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            animationDuration
          }
        ]
      })
    }
  }
}
</script>

<style lang="less" scoped>
@keyframes echartsMoveIn {
  0% {
    opacity: 0;
    transform: translateY(12px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.container {
  width: 100%;
  height: 100%;
  background-color: #f3f5fa;
  display: flex;
  flex-direction: column;

  .statistics {
    display: flex;
    justify-content: space-around;
    padding: 10px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

    .filename {
      color: #409EFF;
      font-weight: bold;
      cursor: pointer;
    }

    .filename:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  .echarts {
    flex: 1;
    margin-top: 10px;

    .top-echarts, .bottom-echarts {
      width: 100%;
      height: 47%;
      display: flex;
      justify-content: space-around;

      .disease-bar, .word-cloud, .age-funnel, .gender-pie {
        width: 49%;
        height: 100%;
        background-color: #fff;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
        animation: echartsMoveIn .5s cubic-bezier(.4, 0, .2, 1) forwards;
      }
    }
  }
}

.tips {
  width: 100%;
  display: flex;
  align-items: center;

  .tips-icon {
    width: 20px;
    height: 20px
  }

  .tips-text {
    font-size: 14px;
    margin-left: 5px;
    font-weight: bold;
  }
}

.upload-file {
  width: 100%;

  /deep/ .el-upload {
    width: 100%;
  }

  /deep/ .el-upload .el-upload-dragger {
    width: 100%;
  }
}
</style>